package com.wesh.gateway.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.function.Predicate;

/**
 * 自定义断言，检查用户信息
 */
@Component
public class CheckUserRoutePredicateFactory extends AbstractRoutePredicateFactory<PredicateConfig> {

    private final Logger logger = LoggerFactory.getLogger(CheckUserRoutePredicateFactory.class);

    public CheckUserRoutePredicateFactory() {
        super(PredicateConfig.class);
    }

    /**
     * 重新 apply 方法
     * @param config
     * @return
     */
    @Override
    public Predicate<ServerWebExchange> apply(PredicateConfig config) {
        return (GatewayPredicate) serverWebExchange -> {
            MultiValueMap<String, String> queryParams = serverWebExchange.getRequest().getQueryParams();
            if(queryParams.containsKey(config.getName())){
                String username = queryParams.getFirst(config.getName());
                if(!StringUtils.isEmpty(username)){
                    logger.info("检查用户信息是否合法 {}", username);
                    if(username.length() > 4){
                        return true;
                    }
                }
            }
            return false;
        };
    }
}


